package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.SMSUtils;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate<Object, Object> redisTemplate;
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpServletRequest request){
        String phone = user.getPhone();
        String checkCode = String.valueOf(RandomUtils.nextInt(900000) + 100000);
        log.info(checkCode);
//        SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",user.getPhone(), String.valueOf(checkCode));
        request.getSession().setAttribute(user.getPhone(),checkCode);
        redisTemplate.opsForValue().set(phone,checkCode,3L, TimeUnit.MINUTES);
        return R.success("验证码发送成功");
    }

    @PostMapping("/login")
    @Transactional
    public R login(@RequestBody Map map, HttpServletRequest request){
        String phone = (String) map.get("phone");
        String inputCode = (String) map.get("code");
        String code = (String) redisTemplate.opsForValue().get(phone);
//        String code = (String) request.getSession().getAttribute(phone);
        if(inputCode.equals(code)){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if(user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            Long id = user.getId();
            System.out.println(user.getId());
            request.getSession().setAttribute("user",id);
            redisTemplate.delete(phone);
            return R.success("登录成功");
        }
        return R.error("登录失败");

    }

    @PostMapping("/loginout")
    public R logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
}
